/* 自定义 MLoading */
app.factory('mLoading',['$http',function($http){
    // var dm = window.dm || {loading:function(){}};
    return {};
}]);

/* 自定义 MNotice */
app.factory('mNotice',function(){
    // var dm = window.dm || {notice:function(){}};
    return {};
});
app.factory('Message',function(){
    // var dm = window.dm || {notice:function(){}};
    return {};
});
/* 
    自定义ajax 
    @params
        _expire:1405492661238 //过期时间戳

*/
app.factory('http', ['$http', '$q','mLoading','Message',
    function($http, $q ,mLoading , Message) {
        var Cache = {};
        var http = window['http'] = {
            ajax: function(url, data, opts,successCallback, failCallback,always) {
                var self = this,
                    opts = opts || {},
                    data = data || {},
                    deferred = $q.defer(),
                    method = opts.type || 'GET',
                    dataType = opts.dataType || 'json',
                    timeout = opts.timeout || 60 * 1000,
                    context = opts.context || self,
                    expire = data._expire,// 数据保留时间
                    now = new Date().valueOf(),
                    params = jQuery.param(data),
                    cache_url = url + '?' + params,
                    result,
                    config = {};

       
                /*if('GET' === method && expire && Cache[cache_url] && ( now-Cache[cache_url]['t']<expire ) ) {
                    result = Cache[cache_url]['data'];
                    successCallback && successCallback(result);
                    deferred.resolve(result);
                    always && always();

                    return deferred.promise;
                }*/
                delete data._expire;
                config = {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    transformRequest: function(obj) {
                        return jQuery.param(obj);
                    },
                    method: method,
                    url: url,                        
                    dataType: dataType,
                    data: data

                };
                if (method === 'POST') {
                    config.data = data;
                } else {
                    config.params = data;
                }

                $http(config).success(function(data, status, headers, config) {
                    var message = 'something error';
            
                    if (data.code && data.code != 0) {
                      // 登录失效
                      
                        
                        deferred.reject({
                            status:status,
                            message: message
                        });

                        
                    } else {
                        if(expire){
                            Cache[cache_url] = {
                                data:data,
                                t:now
                            };
                        }
                        successCallback && successCallback(data);
                        deferred.resolve(data);
                        always && always();
                    }


                }).error(function(data, status, headers, config) {
                    var message = 'error';
                    var data = data || {};
                    // console.warn(data)
                    if(data.code && data.code != 0){
                        message = data.message;
                        
                    }else {
                        data = {
                            message: '服务器出错'
                        };
                        
                    }
                    // 错误提醒
                    Message.show(config.url+' '+data.message,'error');
                    failCallback && failCallback(data);
                    deferred.reject({
                        status:status,
                        message: message
                    });
                    always && always();

                });

                return deferred.promise;
            },
            get: function(url, data,successCallback, failCallback,always) {

                return this.ajax(url, data, {
                    type: 'GET'
                },successCallback, failCallback,always);

            },
            post: function(url, data, successCallback, failCallback,always) {
                var type = 'POST';
                if(location.href.indexOf('localhost')>-1){
                    type = 'GET';
                }
                return this.ajax(url, data, {
                    type: type
                },successCallback, failCallback,always);

            },
            // 处理请求错误
            handleXhrError: function(xhr) {
                var responseText,
                    error = {},
                    isResponseObject = function(xhr) {
                        return /^{/.test(xhr.responseText);
                    };

                if (xhr.statusText === 'timeout') {
                    error.message = '请求超时 ';
                } else if (xhr.message) {
                    error = xhr;
                } else if (xhr.status == 500 && isResponseObject(xhr)) {
                    try {
                        responseText = xhr.responseText.replace('/\\/g', '//');
                        error = $.parseJSON(responseText);
                        error.message = error.message || '错误未知';

                    } catch (e) {
                        console.warn('responseText parse error');
                        error = {
                            message: ' 错误未知 '
                        };
                    }

                } else {
                    error = {
                        message: ' 错误未知 '
                    };
                }

                error.status = xhr.status;

                return error;
            }

        };

        return http;


    }
]);
/*
        自定义resource 封装api请求
    *   @param url --> string ajax路径 example:假设完整路径 'http://m.igrow.cn/api/1.1b/school/people/get' 则url为'/school/people'
    *   @param options --> object 暂时没用
    *   @param actions --> object example :{ 'get2': { method:'GET',params:{ '默认参数1':'1','默认参数2':'2' } } }
    *
    *  默认返回的对象包含的方法:get,update,create,list,search,_delete   
    *  调用example
    *  var schoolPeople = resource('/school/people',{},{});
    *  schoolPeople.get({id:'1'}), function(result){
    *      console.log('返回的数据',result.data) ;
    *      
    *  },function(result){
    *      console.log( '错误信息',result.message );
    *  },function(){
    *      console.log('always')
    *  });
*/
app.factory('resource', ['http',
    function(http) {
        var page = '_page';
        var pagesize = '_pagesize';
        var API = window.API || {};

        var checkURL = function(url){
            var prefix = API.prefix || '';
            var api = (API.host || ('http://' + location.host)) + '/';
            var ext = api.indexOf('local')>-1?'.json':'';

             
            api = prefix?(api+prefix+'/'):api;

            //console.log('request url: ',api,url,ext);
            return (api+url+ext);
        };
        
        var $resource = function(url, options, actions) {
            var url = url || '',
                options = options || {}, actions = actions || {},
                resourse = {}, params;

            
            resourse = {
                url: url,
                request:function(name,data,options){
                    var url = name,
                        options = options || {},
                        method = options.method?options.method:'post',
                        data = data || {};

                    
                    return http[method](url, data);

                },
                invoke:function(name,data,options,successCallback,failCallback){
        
                    var url = name?this.url + '/' +name:this.url,
                        method = options || 'post',
                        data = data || {};

                    url = checkURL(url);
                    return http[method](url, data,successCallback,failCallback);

                },
                list: function(data, successCallback, failCallback,always) {
                    var url = this.url + '/list',
                        data = data || {};

                    // data[page] = data._page ? data._page : 1;
                    // data[pagesize] = data._pagesize ? data._pagesize : 20;
                    url = checkURL(url);

                    return http.get(url, data ,successCallback, failCallback,always);
                },
                get: function(name,data, successCallback, failCallback,always) {
                    var url = name?this.url + '/' +name:this.url,
                        
                        data = data || {};

                    url = checkURL(url);
                    return http.get(url, data, successCallback, failCallback,always);
                },
                search: function(data, successCallback, failCallback,always) {
                    var url = this.url + '/search',
                        data = data || {};

                    // data[page] = data._page ? data._page : 1;
                    // data[pagesize] = data._pagesize ? data._pagesize : 20;
                    url = checkURL(url);

                    return http.get(url, data,successCallback, failCallback,always);
                },
                _delete: function(data, successCallback, failCallback,always) {
                    var url = this.url + '/delete',
                        data = data || {};

                    url = checkURL(url);

                    return http.get(url, data,successCallback, failCallback,always);
                },
                create: function(data, successCallback, failCallback,always) {
                    var url = this.url + '/create',
                        data = data || {};

                    url = checkURL(url);

                    return http.post(url, data,successCallback, failCallback,always);
                },
                update: function(data, successCallback, failCallback,always) {
                    var url = this.url + '/update',
                        data = data || {};

                    url = checkURL(url);
                    return http.post(url, data,successCallback, failCallback,always);
                }
            };
            // 自定义action
            for (var action in actions) {
                var opts = actions[action] || {}, method = opts.method || "GET",
                    params = opts.params || {};

                method = method.toLowerCase();
                resourse[action] = (function(url, action, method, params) {

                    return function(data, successCallback, failCallback,always) {
                        var data = data || {};

                        url = resourse['url'] + '/' + action;
                        url = checkURL(url);
                        data = jQuery.extend({}, params, data);

                        return http[method](url, data, successCallback, failCallback,always);

                    };

                })(url, action, method, params)

            };



            return resourse;

        };

        return $resource;
    }
]);

/**
 * 日历插件 YYYY-MM-DD hh:mm:ss
 */
app.directive('laydate', ['uiLoad',function (uiLoad) {
    return {
        restrict: 'AE',
        scope: {
            config: '=laydateConfig'
        },
        require: 'ngModel',
        link: function (scope, element, attr, ngModel) {
            uiLoad.load('vendor/laydate/laydate.js').then(function(){
                var defs = {
                    format: 'YYYY-MM-DD',
                    istoday: false,
                    choose: function(datas){ 
                        // 选择日期完毕的回调
                        // alert('得到：'+datas);
                        console.log('datas',datas)
                        ngModel.$setViewValue(datas)
                    }
                };
                // 获取当前的DOM元素
                var _dom = element[0];
                var config2 = attr.laydate?JSON.parse(attr.laydate):{};
                var config1 = scope.config || {};
                var config = $.extend(defs,config1,config2);

                
                
                element.on('clear',function(){
                    ngModel.$setViewValue('')
                });
                _dom.onclick = function(){
                     $(document).off('click.clear').on('click.clear','#laydate_clear',function(){
                        element.trigger('clear');
                     });
                     laydate(config)
                }

                ngModel.$render = function() {
                    modelContent = (ngModel.$isEmpty(ngModel.$viewValue) ? "" : ngModel.$viewValue);
                    _dom.value = modelContent
                };
              
              
            });
            
                
            

        }
    }
}]);

/**
 * 编辑器UMeditor
 */
app.directive('metaUmeditor', ['uiLoad',function (uiLoad) {
    return {
        restrict: 'AE',
        scope: {
            config: '=metaUmeditorConfig'
        },
        require: 'ngModel',
        transclude: true,
        link: function (scope, element, attr, ngModel) {

            uiLoad.load('vendor/umeditor/umeditor.min.js').then(function(){
                // 获取当前的DOM元素
                var _dom = element[0];
                var modelContent,_updateByRender,editorReady;
                var _placeholder = '';
                var _id = attr.id ? attr.id : "_editor" + Math.floor(Math.random() * 100).toString() + (Date.now());
                
                var _config = scope.config || {
                        // 这里可以选择自己需要的工具按钮名称,此处仅选择如下七个
                        toolbar: ['source undo redo bold italic underline'],
                        // focus时自动清空初始化时的内容
                        autoClearinitialContent: true,
                        // 关闭字数统计
                        wordCount: false,
                        // 关闭elementPath
                        elementPathEnabled: false,
                        // frame高度
                        // initialFrameHeight: 300
                    };


                _dom.setAttribute('id', _id);

                var _umeditor = UM.getEditor(_id, _config);

                /**
                 * 对于umeditor添加内容改变事件，内容改变触发ngModel改变.
                 */
                var editorToModel = function () {
                    
                    if (_umeditor.hasContents()){

                        ngModel.$setViewValue(_umeditor.getContent());
                    }
                    else{
                        ngModel.$setViewValue(undefined);
                    }
                    _updateByRender = false;
                };

                /**
                 * umeditor准备就绪后，执行逻辑
                 * 如果ngModel存在
                 *   则给在编辑器中赋值
                 *   给编辑器添加内容改变的监听事件.
                 * 如果不存在
                 *   则写入提示文案
                 */

                _umeditor.ready(function () {
                    editorReady = true;
                    // console.log('ready',ngModel.$viewValue)
                    if (ngModel.$viewValue) {
                        _umeditor.setContent(ngModel.$viewValue);
                        
                    } else {
                        _umeditor.setContent(_placeholder);
                    }
                    _umeditor.addListener('contentChange', editorToModel);
                    //_umeditor.execCommand('fontsize', '32px');
                    //_umeditor.execCommand('fontfamily', '"Microsoft YaHei","微软雅黑"')
                });


                
                function setEditorContent(content){
                    //console.log(_umeditor,1,content)
                    if(content && editorReady){
                        _umeditor.setContent(content)
                    }
                }
                ngModel.$render = function() {
                    _updateByRender = true;
                    modelContent = (ngModel.$isEmpty(ngModel.$viewValue) ? "" : ngModel.$viewValue);
                    setEditorContent(modelContent);
                };
                
                scope.$on("$destroy", function() {
                    if (UM.delEditor) {
                        UM.delEditor(_id);
                    }
                });
            });
                

        }
    }
}]);

// 上传 require webuploader.js
app.directive('wu',['uiLoad',function(uiLoad){
    return {
            restrict : 'A',
            scope: {
                config: '=wuConfig'
            },
            require: '?ngModel',
            link:function(scope, element, attr, ngModel){
                var api = window.API || {};
                uiLoad.load('vendor/webuploader/webuploader.html5only.min.js').then(function(){
                    var $wu = element.wu();
                    
                    $wu.on('success',function(event,result){
                      var response = result.response,file = result.file, path = response.path;
                      ngModel.$setViewValue(path)
                    });
                    $wu.on('delete',function(event,file){
                      ngModel.$setViewValue('')
                    });

                    ngModel.$render = function() {
                        content = (ngModel.$isEmpty(ngModel.$viewValue) ? "" : ngModel.$viewValue);
                        content && $wu.triggerHandler('files',content);
                    };
                });
                    

            }
    }; 
}]);
 

